package com.codefish.codefishseckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codefish.codefishseckill.entity.AuthUser;
import com.codefish.codefishseckill.entity.User;
import com.codefish.codefishseckill.mapper.UserMapper;
import com.codefish.codefishseckill.utils.MD5PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/30 下午 04:36
 */
@Service("userDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<User> query = new QueryWrapper<>();
        query.select("password", "salt", "nickname", "username", "identification").eq("username", username);
        User user = userMapper.selectOne(query);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        //更新password，将盐值也包含进去
        user.setPassword(MD5PasswordUtil.concatPasswordAndSalt(user.getPassword(), user.getSalt()));

        return new AuthUser(user);
    }

}
